/*
 * intro.c
 */

#include <utils/png_utils.h>
#include <gui/gui.h>
#include <rowgage.h>
#include "intro.h"
#include "graphics.h"

#define INTRO_FILE "img/intro.png"

static GLuint intro_screen;
static GLsizei intro_width;
static GLsizei intro_height;

/*
 * Stored keyboard function. This function is set as the keyboard function
 * when the intro is enabled.
 */
static void (*keyboard_func)(unsigned char key, int x, int y);

/*
 * Draws the introduction screen.
 */
void intro_draw() {
    GLint vPort[4];
    float midpoint_x;
    float midpoint_y;
    float half_width;
    float half_height;

    glGetIntegerv(GL_VIEWPORT, vPort);
    midpoint_x = ( vPort[0] + vPort[2] ) / 2.0f;
    midpoint_y = ( vPort[1] + vPort[3] ) / 2.0f;
    half_width = ((float)intro_width) / 2.0f;
    half_height = ((float)intro_height) / 2.0f;

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, intro_screen);

    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    glBegin(GL_QUADS);
        glTexCoord2f( 0.0f, 0.0f );
        glVertex2f( midpoint_x - half_width, midpoint_y - half_height );

        glTexCoord2f( 1.0f, 0.0f );
        glVertex2f( midpoint_x + half_width, midpoint_y - half_height );

        glTexCoord2f( 1.0f, 1.0f );
        glVertex2f( midpoint_x + half_width, midpoint_y + half_height );

        glTexCoord2f( 0.0f, 1.0f );
        glVertex2f( midpoint_x - half_width, midpoint_y + half_height );
    glEnd();

    glDisable(GL_TEXTURE_2D);
}

/*
 * The keyboard function for the introduction screen.
 */
void intro_keyboard( unsigned char key, int x, int y ) {
    switch(key) {
        case 'g': intro_disable();
    }
}

/*
 * Enables the introduction, ceasing normal gameplay until the intro is
 * disabled.
 */
int intro_enable( void (*f)(unsigned char key, int x, int y) ) {
    keyboard_func = f;
    intro_screen = loadPNGTextureWH( INTRO_FILE, &intro_width, &intro_height );
    graphics_set_draw_alt(intro_draw);
    graphics_swap_draw();
    rgBackListReset();
    rgAddBackCallback(nextAnimationFrame);
    rgSetKeyboardCallback(intro_keyboard);
    rgCallbackSwap();
    return 0;
}

/*
 * Disables the introduction, resuming normal gameplay.
 */
int intro_disable() {
    graphics_swap_draw();
    rgCallbackSwap();
    rgSetKeyboardCallback(keyboard_func);
    return 0;
}
